package com.edou.base.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.edou.base.wrapper.TocerRequestWrapper;

/**
 * 基础过滤器，目前实现的功能：
 * 1.字符集过滤，设置为指定编码格式
 * 2.trim过滤，参数前后空格剔除
 * @creator     admin
 * @create-time 2017年8月7日   下午2:46:24
 * @email admin@edou.com
 * @company www.edou.com
 * @version 1.0
 */
public class TocerBaseFilter implements Filter{
	
	/** 编码格式 */
	private String encoding;
	/** 默认字符集 */
	private final String defaultEncoding = "utf-8";

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.encoding = filterConfig.getInitParameter("encoding");
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		//1.设置字符集过滤
		if(null != this.encoding && this.encoding.length() > 0) {
			request.setCharacterEncoding(this.encoding);
		}else {
			request.setCharacterEncoding(this.defaultEncoding);
		}
		
		//2.过滤参数空格
		TocerRequestWrapper tocerRequestWrapper = new TocerRequestWrapper(request);
		
		//3.继续执行后续拦截器
		chain.doFilter(tocerRequestWrapper,res);
	}

	@Override
	public void destroy() {
		
	}

}
